import { computed, ref } from 'vue';
import { useRouter } from 'vue-router';
import { defineStore } from 'pinia';
import md5 from 'md5';
import { loginUser, getUserProfile, registerUser } from '@/api';
import { MMessage } from '@/libs';
import { LOGIN_TYPE_OAUTH_NO_REGISTER } from '@/constants';

const useUserStore = defineStore(
  'user',
  () => {
    const router = useRouter();

    const token = ref<string>('');
    const userInfo = ref<
      | {
          [key in
            | 'avatar'
            | 'company'
            | 'homePage'
            | 'introduction'
            | 'nickname'
            | 'outTradeNo'
            | 'outTradeNo'
            | 'payResult'
            | 'false'
            | 'qqOpenId'
            | 'regTime'
            | 'title'
            | 'username'
            | 'vipLevel'
            | 'wxOpenId'
            | '__v'
            | '_id']: string;
        }
      | null
    >(null);

    const tokenGetter = computed(() => token.value);
    const userInfoGetter = computed(() => userInfo.value);

    const updateToken = (newToken: string) => {
      token.value = newToken;
    };
    const updateUserInfo = (newUserInfo: any) => {
      userInfo.value = newUserInfo;
    };

    const login = async (payload: {
      username: string;
      password: string;
      loginType: 'username' | 'QQ' | 'WX';
      [key: string]: any;
    }) => {
      const { token, code } = await loginUser<{
        token: string;
        code: number | string;
      }>({
        ...payload,
        password: payload.password ? md5(payload.password) : ''
      });

      if (code === LOGIN_TYPE_OAUTH_NO_REGISTER) {
        return code;
      }

      updateToken(token);

      getUserInfo();
    };

    const register = async (payload: {
      username: string;
      password: string;
    }) => {
      return await registerUser({
        ...payload,
        password: payload.password ? md5(payload.password) : ''
      });
    };

    const logout = async () => {
      token.value = '';
      userInfo.value = null;

      router.push({ path: '/login' });
      // location.reload();
    };
    const getUserInfo = async () => {
      const userInfo = await getUserProfile<{
        [key in
          | 'avatar'
          | 'company'
          | 'homePage'
          | 'introduction'
          | 'nickname'
          | 'outTradeNo'
          | 'outTradeNo'
          | 'payResult'
          | 'false'
          | 'qqOpenId'
          | 'regTime'
          | 'title'
          | 'username'
          | 'vipLevel'
          | 'wxOpenId'
          | '__v'
          | '_id']: string;
      }>();

      updateUserInfo(userInfo);
      MMessage({
        type: 'success',
        content: `欢迎您 ${userInfo.vipLevel ? '尊贵的vip' + userInfo.vipLevel + '用户' + userInfo.nickname : userInfo.nickname}`,
        duration: 6000
      });
    };

    return {
      token,
      tokenGetter,
      register,
      login,
      logout,
      userInfo,
      userInfoGetter,
      getUserInfo,
      updateUserInfo
    };
  },
  {
    persist: [
      {
        pick: ['token', 'userInfo'],
        storage: localStorage
      }
    ]
  }
);

export default useUserStore;
